package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/russross/blackfriday/v2"
	"html/template"
	"myblog/dao"
	"myblog/model"
	"strconv"
)

func GoLogin(c *gin.Context) {
	c.HTML(200, "login.html", nil)
}

func AddUser(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := model.User{
		Username: username,
		Password: password,
	}
	dao.Mgr.AddUser(&user)
	c.HTML(200, "login.html", nil)
}

func FindUser(c *gin.Context) {
	username := c.PostForm("usernameIn")
	password := c.PostForm("passwordIn")
	user := dao.Mgr.FindUser(username, password)
	if user.Username != "" {
		if user.Password == password {
			c.Redirect(301, "/index")
		} else {
			c.String(200, "密码错误")
		}
	} else {
		c.String(200, "用户名错误")
	}
}

func Index(c *gin.Context) {
	c.HTML(200, "index.html", nil)
}

func GoBlog(c *gin.Context) {
	c.HTML(200, "addblog.html", nil)
}

func AddBlog(c *gin.Context) {
	title := c.PostForm("title")
	tag := c.PostForm("tag")
	img, _ := c.FormFile("bolgImg")
	content := c.PostForm("content")

	blog := model.Blog{
		Title:   title,
		Tag:     tag,
		Img:     img.Filename,
		Content: content,
	}
	file := "./assets/img/" + img.Filename
	err := c.SaveUploadedFile(img, file)
	if err != nil {
		return
	}
	dao.Mgr.AddBlog(&blog)
	c.HTML(200, "bloglist.html", nil)
}

func Showblog(c *gin.Context) {
	var blogList []model.Blog
	bl := dao.Mgr.FindAll(blogList)
	c.HTML(200, "bloglist.html", gin.H{
		"blog": bl,
	})
}

func Details(c *gin.Context) {
	s := c.Query("id")
	fmt.Printf("---------------%s\n", s)
	id, _ := strconv.Atoi(s)
	b := dao.Mgr.FindBlog(id)
	fmt.Print(b)
	content := blackfriday.Run([]byte(b.Content))
	c.HTML(200, "details.html", gin.H{
		"title":   b.Title,
		"content": template.HTML(content),
	})
}
